// import JSEncrypt from "jsencrypt";
import JSEncrypt from "jsencrypt/bin/jsencrypt.min";
import moment from "moment";

export const __FUNC__ = {
  format: function (timeStamp) {
    //timeStamp是整数，否则要parseInt转换
    var time = new Date(timeStamp);
    console.log(time);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return (
      y +
      "-" +
      __FUNC__.trans(m) +
      "-" +
      __FUNC__.trans(d) +
      " " +
      __FUNC__.trans(h) +
      ":" +
      __FUNC__.trans(mm) +
      ":" +
      __FUNC__.trans(s)
    );
  },
  trans: function (m) {
    return m < 10 ? "0" + m : m;
  },
  randomData: function (min, max) {
    if (max == undefined) {
      if (min == undefined) min = 10;
      min = parseInt(min);
      return Math.round(Math.random() * min);
    } else {
      min = parseInt(min);
      max = parseInt(max);
      return min + Math.round((max - min) * Math.random());
    }
  },
  //sum分解为times个随机数（简称红包算法）
  getSumToMoreRandomData: function (sum, times) {
    var res = [];
    if (times === 1) {
      res.push(sum);
      return res;
    }
    var max = (sum / times) * 2;
    var current = 1 + ~~(Math.random() * max - 1);
    res.push(current);
    return res.concat(__FUNC__.getSumToMoreRandomData(sum - current, --times));
  },
  keepDecimal: function (val, num) {
    if (num == undefined) num = 1;
    var pow = Math.pow(10, num);
    var rtn = Math.round(val * pow) / pow;
    return rtn;
  },
  /*
   * 通用性：通用
   * 方法说明：动态生成表单提交
   * 参数说明：url：提交地址；obj：需要提交的参数；target：页面如何呈现；method：表单提交方式
   */
  openPostWindow: function (url, obj, target, method) {
    var tempForm = document.createElement("form");
    // if (obj.csrfmiddlewaretoken == undefined) {
    //     obj.csrfmiddlewaretoken = $.cookie("csrftoken")
    // }
    tempForm.id = "tempForm1";
    tempForm.method = method == undefined ? "get" : method;
    tempForm.action = url;
    tempForm.target = target == undefined ? "_self" : target; //打开新页面
    for (var i in obj) {
      var hideInput = document.createElement("input");
      hideInput.type = "hidden";
      hideInput.name = i; //后台要接收这个参数来取值
      hideInput.value = obj[i]; //后台实际取到的值
      tempForm.appendChild(hideInput);
    }
    if (document.all) {
      tempForm.attachEvent("onsubmit", function () {}); //IE
    } else {
      var subObj = tempForm.addEventListener("submit", function () {}, false); //firefox
    }
    document.body.appendChild(tempForm);
    if (document.all) {
      tempForm.fireEvent("onsubmit");
    } else {
      var evt = document.createEvent("HTMLEvents");
      evt.initEvent("submit", false, false);
      tempForm.dispatchEvent(evt);
    }
    tempForm.submit();
    document.body.removeChild(tempForm);
  },
  //十六进制颜色转rgba，只接收#xxx或者#xxxxxx
  hex2Rgba: function (color, opacity) {
    var reg_hex = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
    var sColor = color.toLowerCase();
    if (sColor && reg_hex.test(sColor)) {
      if (sColor.length === 4) {
        var nColor = "#";
        for (var i = 1; i < 4; i++) {
          nColor += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
        }
        sColor = nColor;
      }
      var sColorArr = [];
      for (var i = 1; i < 7; i += 2) {
        sColorArr.push(parseInt("0x" + sColor.slice(i, i + 2)));
      }
      return (
        "rgba(" +
        sColorArr.join(",") +
        "," +
        (opacity ? parseFloat(opacity) : 1) +
        ")"
      );
    } else {
      return sColor;
    }
  },
  //image file转base64
  fileToBase64(file, callback) {
    const reader = new FileReader();
    reader.addEventListener("load", () => callback(reader.result));
    reader.readAsDataURL(file);
  },
  //判断是否是图片
  isImageByName: function (
    filename,
    acceptTypes = ["jpg", "png", "bmp", "gif", "jpeg", "webp"]
  ) {
    if (!filename) return false;
    let _suffix = filename.substr(filename.lastIndexOf(".") + 1).toLowerCase();
    return acceptTypes.includes(_suffix);
  },
  //html转码
  htmlEncode: function (str) {
    var s = "";
    if (str.length == 0) return "";
    s = str.replace(/&/g, "&amp;");
    s = s.replace(/</g, "&lt;");
    s = s.replace(/>/g, "&gt;");
    s = s.replace(/ /g, "&nbsp;");
    s = s.replace(/\'/g, "&#39;");
    s = s.replace(/\"/g, "&quot;");
    //...
    return s;
  },
  //html解码
  htmlDecode: function (str) {
    var s = "";
    if (str.length == 0) return "";
    s = str.replace(/&amp;/g, "&");
    s = s.replace(/&lt;/g, "<");
    s = s.replace(/&gt;/g, ">");
    s = s.replace(/&nbsp;/g, " ");
    s = s.replace(/&#39;/g, "'");
    s = s.replace(/&quot;/g, '"');
    //...
    return s;
  },
  //深度合并两个对象
  deepMergeObject: function (FirstOBJ, SecondOBJ) {
    // 深度合并对象
    for (var key in SecondOBJ) {
      FirstOBJ[key] =
        FirstOBJ[key] && FirstOBJ[key].toString() === "[object Object]"
          ? __FUNC__.deepMergeObject(FirstOBJ[key], SecondOBJ[key])
          : (FirstOBJ[key] = SecondOBJ[key]);
    }
    return FirstOBJ;
  },
  //深度查找节点，返回true / false
  findTarget(obj, target, key) {
    if (!key) key = "name";
    for (const index in obj) {
      const element = obj[index];

      if (element[key] == target) {
        return true;
      }
      if (element.children && element.children.length) {
        if (this.findTarget(element.children, target, key)) {
          return true;
        }
      }
    }
  },
  //设置存储
  setLocalStorage(key, value) {
    window.localStorage.setItem(key, value);
    return value;
  },
  //获取存储
  getLocalStorage(key) {
    return window.localStorage.getItem(key);
  },
  // 密码加密
  rsaEncryptedData: function (data) {
    let jsencrypt = new JSEncrypt();
    jsencrypt.setPublicKey(data.public_key);
    // 如果是对象/数组的话，需要先JSON.stringify转换成字符串
    var result = jsencrypt.encrypt(data.password.toString());
    return result;
  },
  //匹配权限菜单
  getAuthMenus: function (authRouters = [], allRouters = []) {
    var realRoutes = [];
    allRouters.forEach((v, i) => {
      authRouters.forEach((w, j) => {
        if (w.name === v.name) {
          if (w.children && w.children.length > 0) {
            v.children = this.getAuthMenus(w.children, v.children);
          }
          realRoutes.push(v);
        }
      });
    });
    return realRoutes;
  },
  //base64转文件流
  base64toFile(dataurl, filename) {
    let arr = dataurl.split(",");
    let mime = arr[0].match(/:(.*?);/)[1];
    let suffix = mime.split("/")[1];
    let bstr = atob(arr[1]);
    let n = bstr.length;
    let u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], `${filename}.${suffix}`, {
      type: mime,
    });
  },
  //blob下载
  blobToFile(content, filename = "file.xlsx") {
    const blob = new Blob([content]),
      a = document.createElement("a"),
      url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = filename;
    a.click();
    window.URL.revokeObjectURL(url);
  },
  // 导出文件流
  downloadFile(params, url) {
    var url = url;
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // xhr.setRequestHeader("X-CSRFtoken", $.cookie("csrftoken"));
    xhr.responseType = "blob";
    xhr.onload = function () {
      // canDownLoad = true;
      // $('.panel-body').find('.datagrid-wrap .datagrid-loading').remove();
      console.log(xhr.getResponseHeader("filename"));
      if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
        var fileName = decodeURI(xhr.getResponseHeader("filename"));
        //校验是否下载参数
        var content = xhr.response;
        if (!fileName || fileName === "null") {
          var myReader = new FileReader();
          myReader.addEventListener("loadend", function (e) {
            var msg = e.srcElement.result;
            // Dialogs.showWarn(msg);
          });
          myReader.readAsText(content);
          return;
        }
        //数据转换为文件下载
        var elink = document.createElement("a");
        elink.download = fileName || "demo.xlsx";
        elink.style.display = "none";
        var blob = new Blob([content]);
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
      } else {
        alert("导出失败（500）");
        //此处为错误处理方法
      }
    };
    var pp = "";
    for (var key in params) {
      if (pp === "") {
        pp += key + "=" + params[key];
      } else {
        pp += "&" + key + "=" + params[key];
      }
    }
    xhr.send(pp);
  },

  //文件新开页签下载
  downloadFileInNewTab(url, params) {
    Object.keys(params).forEach((key, i) => {
      let _symbol = i == 0 ? "?" : "&";
      url += `${_symbol}${key}=${params[key]}`;
    });
    window.open(url, "_balnk");
  },
  //搜索结果存储   newValue 搜索值  maxLength 搜索结果数量
  insertSearchWord: function (newValue, maxLength = 10) {
    const searchList = JSON.parse(
      localStorage.getItem("global_search_list") || "[]"
    );
    const newValueIndex = searchList.findIndex((item) => item === newValue);
    if (newValueIndex === 0) {
      return;
    }
    if (newValueIndex > 0) {
      searchList.splice(newValueIndex, 1); //删掉这个数
    }
    searchList.unshift(newValue); //把这条数据存储到数组中的第一个位置上
    if (searchList.length > maxLength) {
      searchList.splice(maxLength);
    }
    localStorage.setItem("global_search_list", JSON.stringify(searchList));
    return searchList;
  },
  //判断是否是图片
  isImageByName: function (filename) {
    let _suffix = filename.substr(filename.lastIndexOf(".") + 1).toLowerCase();
    return ["jpg", "png", "bmp", "gif", "jpeg", "webp"].includes(_suffix);
  },
  //数字转换为大写金额x
  digitUppercase(n = 0) {
    let fraction = ["角", "分"];
    let digit = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
    let unit = [
      ["元", "万", "亿"],
      ["", "拾", "佰", "仟"],
    ];
    let head = n < 0 ? "欠" : "";
    if (n === "-") {
      return "";
    }

    n = Math.abs(n);
    let s = "";
    for (let i = 0; i < fraction.length; i++) {
      s += (
        digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]
      ).replace(/零./, "");
    }
    s = s || "整";
    n = Math.floor(n);
    for (let i = 0; i < unit[0].length && n > 0; i++) {
      let p = "";
      for (let j = 0; j < unit[1].length && n > 0; j++) {
        p = digit[n % 10] + unit[1][j] + p;
        n = Math.floor(n / 10);
      }
      s = p.replace(/(零.)*零$/, "").replace(/^$/, "零") + unit[0][i] + s;
    }
    return (
      head +
      s
        .replace(/(零.)*零元/, "元")
        .replace(/(零.)+/g, "零")
        .replace(/^整$/, "零元整")
    );
  },
  // 默认值数据联动返回
  dataLinkage({ params, id, value, selectedOptions, radioOptions }) {
    if (id === params.id) {
      if (
        params.type === "input" ||
        params.type === "number" ||
        params.type === "multiinput" ||
        params.type === "phone" ||
        params.type === "certificates"
      ) {
        let ldzd_tj = params.condition[0].ldzd_tj,
          ldzd_value = params.condition[0].ldzd_value,
          dqzd_value = params.condition[0].dqzd_value,
          _value = params.condition[0].dqzd_tj === "form" ? value : dqzd_value;

        if (ldzd_tj === "eq" && Number(value) === Number(ldzd_value)) {
          return _value;
        } else if (ldzd_tj === "neq" && value !== ldzd_value) {
          return _value;
        } else if (ldzd_tj === "iscon" && value.indexOf(ldzd_value) !== -1) {
          return _value;
        } else if (ldzd_tj === "niscon" && value.indexOf(ldzd_value) == -1) {
          return _value;
        } else if (ldzd_tj === "isnull" && value.trim() === "") {
          return _value;
        } else if (ldzd_tj === "nisnull" && value !== "") {
          return _value;
        } else if (ldzd_tj === "gte" && Number(value) >= Number(ldzd_value)) {
          return _value;
        } else if (ldzd_tj === "lte" && Number(value) <= Number(ldzd_value)) {
          return _value;
        } else {
          return "";
        }
      } else if (params.type == "select" && selectedOptions) {
        let item = params.condition.filter(
          (item) => item.xx_id === selectedOptions.key
        );
        if (item.length !== 0) {
          return item[0].dqzd_tj === "form"
            ? selectedOptions.value || selectedOptions.dyz
            : item[0].dqzd_value;
        } else {
          return "";
        }
      } else if (params.type == "radio" && radioOptions) {
        let item = params.condition.filter(
          (item) => item.xx_id === radioOptions.key
        )[0];

        return item.dqzd_tj === "form" ? radioOptions.value : item.dqzd_value;
      } else if (params.type === "date") {
        let ldzd_tj = params.condition[0].ldzd_tj,
          ldzd_value = params.condition[0].ldzd_value,
          dqzd_value = params.condition[0].dqzd_value,
          timeStamp = moment(value).unix(),
          _value = params.condition[0].dqzd_tj === "form" ? value : dqzd_value;
        console.log(ldzd_tj);
        console.log(timeStamp, "timeStamp");
        console.log(moment(ldzd_value).unix(), "77");

        if (ldzd_tj === "eq" && timeStamp === moment(ldzd_value).unix()) {
          return _value;
        } else if (
          ldzd_tj === "neq" &&
          timeStamp !== moment(ldzd_value).unix()
        ) {
          return _value;
        } else if (
          ldzd_tj === "gte" &&
          timeStamp >= moment(ldzd_value).unix()
        ) {
          return _value;
        } else if (
          ldzd_tj === "lte" &&
          timeStamp <= moment(ldzd_value).unix()
        ) {
          return _value;
        } else if (ldzd_tj === "isnull" && timeStamp === "") {
          return _value;
        } else if (ldzd_tj === "nisnull" && timeStamp !== "") {
          return _value;
        } else if (ldzd_tj === "range") {
          let arr = ldzd_value.split("至");
          if (
            timeStamp >= moment(arr[0]).unix() &&
            timeStamp <= moment(arr[1]).unix()
          ) {
            return _value;
          } else {
            return "";
          }
        } else {
          return "";
        }
      } else {
        return "";
      }
    } else {
      return false;
    }
  },
  // 打乱数组
  shuffle(arr) {
    var length = arr.length,
      randomIndex,
      temp;
    while (length) {
      randomIndex = Math.floor(Math.random() * length--);
      temp = arr[randomIndex];
      arr[randomIndex] = arr[length];
      arr[length] = temp;
    }
    return arr;
  },

  //查出左侧菜单列表，需要传入routes和当前路由路径的字符串
  findSideMenu(routes, path) {
    //处理path，保持格式一致
    if (path.charAt(0) == "/") {
      path = path.substring(1);
    }

    let idx = path.indexOf("/");
    if (idx == -1) return routes;

    let keyword = path.slice(0, idx); //path中当前查找的那一级字符串
    let pathStr = "", //还没有进行查询的path字符串
      obj = {}; //接收当前查到的这一级

    obj = routes.find((item) => {
      return item.path.indexOf(keyword) > -1;
    });
    pathStr = path.substring(idx);
    if (obj?.children) {
      return this.findSideMenu(obj.children, pathStr);
    } else {
      return [];
    }
  },

  getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });
  },

  // 求和解决求和、相减失真
  changeNum(arg1 = "", arg2 = "", isAdd = true) {
    let that = this;
    function changeInteger(arg, r, maxR) {
      if (r != maxR) {
        let addZero = "";
        for (let i = 0; i < maxR - r; i++) {
          addZero += "0";
        }
        arg = Number(arg.toString().replace(".", "") + addZero);
      } else {
        arg = that.getNum(arg);
      }
      return arg;
    }
    let r1, r2, maxR, m;
    r1 = this.getDecimalLength(arg1);
    r2 = this.getDecimalLength(arg2);
    maxR = Math.max(r1, r2);
    arg1 = changeInteger(arg1, r1, maxR);
    arg2 = changeInteger(arg2, r2, maxR);
    m = Math.pow(10, maxR);
    if (isAdd) {
      return (arg1 + arg2) / m;
    } else {
      return (arg1 - arg2) / m;
    }
  },
  getDecimalLength(arg = "") {
    try {
      return arg.toString().split(".")[1].length;
    } catch (e) {
      return 0;
    }
  },
  getNum(arg = "") {
    return Number(arg.toString().replace(".", ""));
  },
  // 求和解决求和、相减失真完成
  // 身份证校验
  isIdentityId(identityId) {
    var patrn = /(^\d{15}$)|(^\d{17}(\d|X|x)$)/; //长度或格式校验
    //地区校验
    var aCity = {
      11: "北京",
      12: "天津",
      13: "河北",
      14: "山西",
      15: "内蒙古",
      21: "辽宁",
      22: "吉林",
      23: "黑龙江",
      31: "上海",
      32: "江苏",
      33: "浙江",
      34: "安徽",
      35: "福建",
      36: "江西",
      37: "山东",
      41: "河南",
      42: "湖北",
      43: "湖南",
      44: "广东",
      45: "广西",
      46: "海南",
      50: "重庆",
      51: "四川",
      52: "贵州",
      53: "云南",
      54: "西藏",
      61: "陕西",
      62: "甘肃",
      63: "青海",
      64: "宁夏",
      65: "新疆",
      71: "台湾",
      81: "香港",
      82: "澳门",
      91: "国外",
    };
    // 出生日期验证
    var sBirthday = (
        identityId.substr(6, 4) +
        "-" +
        Number(identityId.substr(10, 2)) +
        "-" +
        Number(identityId.substr(12, 2))
      ).replace(/-/g, "/"),
      d = new Date(sBirthday);
    // 身份证号码校验 最后4位  包括最后一位的数字/字母X
    var sum = 0,
      weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
      codes = "10X98765432";
    for (var i = 0; i < identityId.length - 1; i++) {
      sum += identityId[i] * weights[i];
    }
    var last = codes[sum % 11]; //计算出来的最后一位身份证号码

    var errorMsg = "";
    if (identityId === "") {
      errorMsg = "身份证号不能为空";
    } else if (!patrn.exec(identityId)) {
      errorMsg = "你输入的身份证长度或格式错误";
    } else if (!aCity[parseInt(identityId.substr(0, 2))]) {
      errorMsg = "你的身份证地区非法";
    } else if (
      sBirthday !=
      d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate()
    ) {
      errorMsg = "身份证上的出生日期非法";
    } else if (identityId[identityId.length - 1] != last) {
      errorMsg = "你输入的身份证号非法";
    }
    return errorMsg;
  },
};
